package com.bjb.vr.client.utils;

import com.alibaba.fastjson.JSONObject;
import com.bjb.vr.common.constant.SyncDataConstant;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @description:
 * @author: hujingbo
 * @create: 2022-12-09 14:03
 **/
@Slf4j
public class HttpSender {

    /**
     * 发送http请求
     *
     * @param postUrl
     * @param params
     */
    public static void postSync(String postUrl, HashMap<String, String> params) {
        Map<String, Object> resultMap = new HashMap<>();
        OkHttpUtil httpUtil = OkHttpUtil.builder()
                .url(postUrl)
                .addHeader("Content-Type", "application/json; charset=utf-8");
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            httpUtil.addParam(next.getKey(), next.getValue());
        }

        // 发送请求
        httpUtil.post(true).async(new OkHttpUtil.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                JSONObject object = JSONObject.parseObject(data);
                if (object.containsKey(SyncDataConstant.STATUS) && HttpStatus.SC_NOT_FOUND == (Integer) object.get(SyncDataConstant.STATUS)) {
                    log.error("从云端服务器获取数据失败！| 原因: {}", object.get(SyncDataConstant.ERROR));
                    return;
                }
                if (object.containsKey(SyncDataConstant.CODE) && String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR).equals(object.get(SyncDataConstant.CODE))) {
                    log.error("从云端服务器获取数据失败！| 原因: {}", object.get(SyncDataConstant.MESSAGE));
                    return;
                }
                if (object.containsKey(SyncDataConstant.CODE) && String.valueOf(HttpStatus.SC_UNAUTHORIZED).equals(object.get(SyncDataConstant.CODE))) {
                    log.error("从云端服务器获取数据失败！| 原因: {}", object.get(SyncDataConstant.MESSAGE));
                    return;
                }

                log.info("【客户端-->服务端】: 同步数据到云端成功！");
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                log.error("请检查网络连通情况...... {}", errorMsg);
            }
        });
    }
}
